package com.zd.miko.tally.MVP.ModuleTallyList;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;

import com.zd.miko.tally.Bean.TallyItemBean;
import com.zd.miko.tally.R;

import java.util.ArrayList;

/**
 * Created by Miko on 2018/3/14.
 */

public class ItemAdapter extends RecyclerView.Adapter<MyVH> {

    Context context;
    public int currentCheckedPosition = -1;
    public ArrayList<TallyItemBean> data;

    public ItemAdapter(ArrayList<TallyItemBean> data) {
        this.data = data;
    }

    public clickListener listener;

    @Override
    public MyVH onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View view = View.inflate(context, R.layout.item_tally_type, null);
        return new MyVH(view);
    }



    @Override
    public void onBindViewHolder(MyVH holder, int position) {
        int listItemRes = data.get(position).getResId();
        String text = data.get(position).getItemName();

        holder.iv.setBackgroundResource(listItemRes);
        holder.tv.setText(text);

        //首先渲染
        if (currentCheckedPosition == position) {
            holder.iv.setChecked(true);
        } else {
            holder.iv.setChecked(false);
        }
        holder.iv.setOnClickListener(v -> {

            //交叉刷新
            notifyItemChanged(currentCheckedPosition);

            currentCheckedPosition = position;

            notifyItemChanged(currentCheckedPosition);

            listener.onClick(position);
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public interface clickListener {
        void onClick(int position);
    }
}

class MyVH extends RecyclerView.ViewHolder {

    public RadioButton iv;
    public TextView tv;

    MyVH(View itemView) {
        super(itemView);
        iv = itemView.findViewById(R.id.iv);
        tv = itemView.findViewById(R.id.tv);
    }
}
